﻿using System.IO;
using System.Threading;

namespace RapidDownloader.Model.Helpers
{
    class DebugStream : Stream
    {
        private readonly Stream stream;
        private readonly long size;

        internal DebugStream(Stream stream, long size)
        {
            this.size = size;
            this.stream = stream;
        }

        public override bool CanRead
        {
            get
            {
                return true;
            }
        }

        public override bool CanSeek
        {
            get
            {
                return true;
            }
        }

        public override bool CanWrite
        {
            get
            {
                return false;
            }
        }

        public override void Flush()
        {
        }

        public override long Length
        {
            get
            {
                return long.MaxValue;
            }
        }

        public override long Position { get; set; }

        public override int Read(byte[] buffer, int offset, int count)
        {
            Thread.Sleep(1);
            Position += buffer.Length;

            if (Position >= size)
            {
                var retVal = buffer.Length - (int)(Position - size);
                Position = size;

                Dispose();

                return retVal;
            }

            return count;
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            return 0;
        }

        public override void SetLength(long value)
        {
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
        }

        protected override void Dispose(bool disposing)
        {
            stream.Dispose();

            base.Dispose(disposing);
        }
    }
}